import 'dart:typed_data';
import 'dart:ui';
import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_trade/widgets/warn_tips.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/easyloading.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easy_permission/constants.dart';
import 'package:flutter_easy_permission/flutter_easy_permission.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../module_common/widgets/token_widget/token_logo.dart';
import 'package:widgets_to_image/widgets_to_image.dart';

class TradeReceivePage extends StatefulWidget {
  final String contract;
  final String contractType;

  const TradeReceivePage({super.key, required this.contract, required this.contractType});

  @override
  _ReceivePage createState() => _ReceivePage();
}

class _ReceivePage extends State<TradeReceivePage> {
  Widget ReceiveHead(BuildContext context) {
    return Stack(
      children: [
        Row(
          children: [
            Expanded(
                flex: 1,
                child: Container(
                  height: 50.w,
                  alignment: Alignment.center,
                  child: Text(
                    'Receive',
                    style: TextStyle(
                      fontSize: 16.sp,
                      height: 20.w / 16.w,
                      fontWeight: FontWeight.w500,
                      color: Color.fromRGBO(51, 51, 51, 1),
                    ),
                  ),
                ))
          ],
        ),
        Positioned(
          top: 0,
          left: 0,
          child: InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              alignment: Alignment.center,
              child: Image.asset(
                'assets/images/dapp/history_close.png',
                width: 20.w,
                height: 20.w,
              ),
              padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 12.w, bottom: 12.w),
            ),
          ),
        ),
      ],
    );
  }

  FocusManager focusManager = FocusManager();

  void _generatePosterImage(Token token) async {
    try {
      const permissions = [Permissions.CAMERA];
      const permissionGroup = [PermissionGroup.Photos];

      bool isHad = await FlutterEasyPermission.has(perms: permissions, permsGroup: permissionGroup);
      if (!isHad) {
        FlutterEasyPermission.request(
            perms: permissions, permsGroup: permissionGroup, rationale: "Downloading requires your user permissions");
        return;
      }
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PosterWidget(
                  token: token,
                )),
      );
      // _saveLocalImage();
    } catch (e) {
      kaiPrint(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    Token? _token = null;
    if (widget.contractType == TokenType.native.name) {
      _token = context.read<TokenListNotifier>().nativeToken;
    }
    if (widget.contractType == TokenType.token20.name && widget.contract.length > 0) {
      _token = context
          .read<TokenListNotifier>()
          .tokenFungibleList
          .firstWhere((element) => element.contract == widget.contract);
    }
    if (_token == null) {
      return Container();
    }
    print(_token);
    return Scaffold(
      backgroundColor: AppColors.c_F6F6F6,
      appBar: PageHeaderCom(
        title: 'Receive',
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        margin: EdgeInsets.only(bottom: 20.w + MediaQuery.of(context).padding.bottom),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
                child: PublicButton(
                    image: PublicImage(
                      image: 'assets/images/common/download.png',
                      width: 16.w,
                      height: 16.w,
                    ),
                    margin: EdgeInsets.zero,
                    type: ButtonType.white,
                    text: 'Download',
                    onClick: () {
                      _generatePosterImage(_token!);
                      // _generatePosterImage();
                    })),
            SizedBox(
              width: 20.w,
            ),
            Expanded(
                child: PublicButton(
              image: PublicImage(
                image: 'assets/images/common/copy-white.png',
                width: 16.w,
                height: 16.w,
              ),
              margin: EdgeInsets.zero,
              type: ButtonType.private,
              text: 'Copy',
              onClick: () {
                bool isCopySuccess = Utils.copyText(context.read<WalletInfoNotifier>().walletAddress);
                Toast.show(context,
                    position: Dpositon.top,
                    message: isCopySuccess ? 'Copied successfully' : 'Copy failed',
                    status: isCopySuccess ? '1' : '2');
              },
            ))
          ],
        ),
      ),
      body: Container(
        padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 10.w),
        child: Column(
          children: [
            WarnTips(text: "This address only support ${_token.symbol} related assets"),
            SizedBox(
              height: 10.w,
            ),
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  color: AppColors.c_FBFBFB, borderRadius: BorderRadius.vertical(top: Radius.circular(10.w))),
              child: Column(
                children: [
                  SizedBox(
                    height: 20.w,
                  ),
                  ClipOval(
                    child: TokenLogo(
                      token: _token,
                      size: 40.w,
                    ),
                  ),
                  SizedBox(
                    height: 10.w,
                  ),
                  Text(
                    '${_token.symbol}(${_token.getChain()!.name})',
                    style: TextStyle(
                        fontSize: 16.sp,
                        height: 22.w / 16.w,
                        color: Color.fromRGBO(51, 51, 51, 1),
                        fontWeight: FontWeight.w500),
                  ),
                  SizedBox(
                    height: 15.w,
                  ),
                  Stack(
                    children: [
                      Container(
                        width: 186.w,
                        height: 186.w,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage('assets/images/wallet-trade/receive-bg.png'), fit: BoxFit.cover),
                        ),
                        child: QrImageView(
                          data: context.watch<WalletInfoNotifier>().walletAddress,
                          version: 5,
                          size: 165.w,
                        ),
                      ),
                      Positioned(
                        top: 82.w,
                        left: 82.w,
                        child: TokenLogo(
                          token: _token,
                          size: 22.w,
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 20.w,
                  ),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                  color: AppColors.c_white, borderRadius: BorderRadius.vertical(bottom: Radius.circular(10.w))),
              child: Container(
                  padding: EdgeInsets.all(15.w),
                  decoration:
                      BoxDecoration(color: AppColors.c_F6F6F6, borderRadius: BorderRadius.all(Radius.circular(10.w))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Receiving Address',
                        style: TextStyle(
                            fontSize: 12.sp,
                            height: 17.w / 12.w,
                            color: Color.fromRGBO(134, 131, 145, 1),
                            fontWeight: FontWeight.w400),
                      ),
                      SizedBox(
                        height: 5.w,
                      ),
                      Text(
                        context.watch<WalletInfoNotifier>().walletAddress,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 12.sp,
                            height: 16.w / 12.w,
                            fontWeight: FontWeight.w400,
                            color: AppColors.c_333333),
                      )
                    ],
                  )),
            ),
            SizedBox(
              height: 35.w,
            ),
          ],
        ),
      ),
    );
  }
}

class PosterWidget extends StatefulWidget {
  late Token token;

  PosterWidget({super.key, required this.token});

  @override
  _PosterWidget createState() => _PosterWidget();
}

class _PosterWidget extends State<PosterWidget> {
  bool isSaving = false;

  // WidgetsToImageController to access widget
  WidgetsToImageController controller = WidgetsToImageController();

  // to save image bytes of widget
  Uint8List? bytes;

  late Token _token;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _token = widget.token;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      EasyLoading.generateLoadingFuture(_saveLocalImage());
    });
  }

  _saveLocalImage() {
    return Future.delayed(Duration(seconds: 1), () async {
      try {
        if (isSaving == true) {
          return;
        }
        isSaving = true;
        Uint8List? bytes = await controller.capture();
        if (bytes != null) {
          if (mounted) {
            final result = await ImageGallerySaver.saveImage(bytes, name: "kai_receive", isReturnImagePathOfIOS: true);
          }
          Toast.show(context, status: '1', position: Dpositon.top, message: "Saved successfully!");
          return;
        }
        Toast.show(context, status: '2', position: Dpositon.top, message: "Save Failed!");
      } catch (e) {
        print("error $e");
      } finally {
        isSaving = false;
        Navigator.pop(context);
        Navigator.pop(context);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.black,
      body: Align(
        child: WidgetsToImage(
          controller: controller,
          child: Container(
            height: 599.w,
            padding: EdgeInsets.fromLTRB(20.w, 20.w, 20.w, 0),
            decoration: BoxDecoration(
              // image: DecorationImage(image: AssetImage('assets/images/wallet-trade/code-bg.png'), fit: BoxFit.cover),
              gradient: LinearGradient(
                colors: [Color.fromRGBO(105, 66, 255, 1), Color.fromRGBO(132, 101, 254, 1)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Column(
              children: [
                WarnTips(text: 'This address only support ${_token.symbol} related assets'),
                SizedBox(
                  height: 10.w,
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(20.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Stack(
                        clipBehavior: Clip.none,
                        children: [
                          TokenLogo(
                            token: _token,
                            size: 40.w,
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 10.w,
                      ),
                      Text(
                        'Receive ${_token.symbol}(${_token.getChain()!.name})',
                        style: TextStyle(
                            fontSize: 16.sp,
                            height: 22.w / 16.w,
                            color: Color.fromRGBO(51, 51, 51, 1),
                            fontWeight: FontWeight.w500),
                      ),
                      SizedBox(
                        height: 15.w,
                      ),
                      Stack(
                        children: [
                          Container(
                            width: 186.w,
                            height: 186.w,
                            decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: AssetImage('assets/images/wallet-trade/receive-bg.png'), fit: BoxFit.cover)),
                            child: QrImageView(
                              data: context.watch<WalletInfoNotifier>().walletAddress,
                              version: 5,
                              size: 168.w,
                            ),
                          ),
                          Positioned(
                            top: 82.w,
                            left: 82.w,
                            child: TokenLogo(
                              token: _token,
                              size: 22.w,
                            ),
                          )
                        ],
                      ),
                      SizedBox(
                        height: 15.w,
                      ),
                      Container(
                        padding: EdgeInsets.all(15.w),
                        decoration: BoxDecoration(
                            color: AppColors.c_F6F6F6, borderRadius: BorderRadius.all(Radius.circular(10.w))),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              'Receiving Address',
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  height: 17.w / 12.w,
                                  color: Color.fromRGBO(134, 131, 145, 1),
                                  fontWeight: FontWeight.w400),
                            ),
                            SizedBox(
                              height: 4.w,
                            ),
                            Text(
                              context.watch<WalletInfoNotifier>().walletAddress,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 12.sp,
                                  height: 16.w / 12.w,
                                  fontWeight: FontWeight.w400,
                                  color: Color.fromRGBO(51, 51, 51, 1)),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 15.w,
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Image.asset(
                      'assets/images/common/kai.png',
                      width: 52.w,
                      height: 25.w,
                    ),
                    Container(
                      width: 67.w,
                      height: 67.w,
                      decoration: BoxDecoration(
                          color: AppColors.c_white,
                          borderRadius: BorderRadius.all(Radius.circular(5.w)),
                          image: DecorationImage(
                              image: AssetImage('assets/images/wallet-trade/receive-bg.png'), fit: BoxFit.cover)),
                      child: QrImageView(
                        data: 'https://kaichat.io',
                        version: 5,
                        size: 67.w,
                        padding: EdgeInsets.all(5.w),
                        embeddedImage: AssetImage('assets/images/wallet-trade/small-logo.png'),
                        embeddedImageStyle: QrEmbeddedImageStyle(
                          size: Size(12.w, 12.w),
                        ),
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
